package com.iflytek.management.controller;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.iflytek.management.mapper.MessageMapper;
import com.iflytek.management.mapper.SysUserMapper;
import com.iflytek.management.pojo.MessT;
import com.iflytek.management.pojo.Message;
import com.iflytek.management.pojo.SysUser;
import com.iflytek.management.util.MybatisUtil;

@Controller
@RequestMapping(value = "/message")
public class MessageController {

	@RequestMapping(value = "/showAllMessage.do",method = RequestMethod.GET)
	@ResponseBody
	public JSONObject showAllMember() throws IOException {
		MessageMapper messMapper = MybatisUtil.Prepare(MessageMapper.class);
		SysUserMapper userMapper = MybatisUtil.Prepare(SysUserMapper.class);
		JSONObject res = new JSONObject();
		List<Message> allMess = new ArrayList<Message>();
		List<MessT> finalReturn = new ArrayList<MessT>();
		try {
			allMess = messMapper.selectAllMess();
			for(Message mess: allMess) {
				SysUser userT = userMapper.selectByPrimaryKey(mess.getUserid());
				MessT temp = new MessT();
				temp.setMessage(mess.getMessage());
				temp.setTime(mess.getTime());
				temp.setRoleid(userT.getRoleid());
				temp.setUsername(userT.getUsername());
				finalReturn.add(temp);
			}
			
		} catch (Exception e) {
			System.out.println(e);
		}
		res.put("allMess", finalReturn);
		return res;
	}
	
	
	@RequestMapping(value = "/saveMessToDB.do",method = RequestMethod.POST)
	@ResponseBody
	public JSONObject saveMessToDB(@RequestBody Message msg) throws IOException {
		MessageMapper messMapper = MybatisUtil.Prepare(MessageMapper.class);

		JSONObject res = new JSONObject();

		try {
			Date date = new Date();
			Timestamp timeStamp = new Timestamp(date.getTime());
			msg.setTime(timeStamp);
			
			messMapper.insert(msg);
			res.put("msg", "消息插入成功");
			
		} catch (Exception e) {
			System.out.println(e);
			res.put("msg", "消息插入失败");
		}
		return res;
	}
}
